package com.logos.musicframe.ui.javafx;

import com.logos.musicframe.controller.SongPlayHistoryController;
import com.logos.musicframe.resp.SongPlayHistoryResp;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.utils.JavaFxMusicPlayer;
import com.logos.musicframe.utils.SpringContextUtil;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.shape.Rectangle;
import lombok.extern.slf4j.Slf4j;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.function.Consumer;

/**
 * 最近播放页面UI
 */
@Slf4j
public class RecentPlayPageUi {

    private final JavaFxMusicPlayer player;
    private final Consumer<SongsResp> onSongSelected;
    private final SongPlayHistoryController songPlayHistoryController = SpringContextUtil.getBean(SongPlayHistoryController.class);

    public RecentPlayPageUi(JavaFxMusicPlayer player, Consumer<SongsResp> onSongSelected) {
        this.player = player;
        this.onSongSelected = onSongSelected;
    }

    /**
     * 创建最近播放页面
     */
    public VBox createRecentPlayPage() {
        VBox container = new VBox(15);
        container.setPadding(new Insets(20));

        // 标题区域
        HBox titleBox = new HBox();
        titleBox.setAlignment(Pos.CENTER_LEFT);
        titleBox.setPadding(new Insets(0, 0, 15, 0));

        Label titleLabel = new Label("最近播放");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");

        titleBox.getChildren().add(titleLabel);

        // 添加分隔线
        Separator separator = new Separator();
        separator.setStyle("-fx-opacity: 0.6;");

        // 创建加载指示器
        ProgressIndicator loadingIndicator = new ProgressIndicator();
        loadingIndicator.setMaxSize(50, 50);
        VBox loadingBox = new VBox(loadingIndicator);
        loadingBox.setAlignment(Pos.CENTER);
        loadingBox.setPadding(new Insets(50, 0, 0, 0));

        // 添加到容器
        container.getChildren().addAll(titleBox, separator, loadingBox);

        // 异步加载最近播放数据
        loadRecentPlayData(container, loadingBox);

        return container;
    }

    /**
     * 加载最近播放数据
     */
    private void loadRecentPlayData(VBox container, VBox loadingBox) {
        new Thread(() -> {
            try {
                // 调用后端API获取最近播放数据
                Result<List<SongPlayHistoryResp>> result = songPlayHistoryController.query();

                Platform.runLater(() -> {
                    // 移除加载指示器
                    container.getChildren().remove(loadingBox);

                    if (result.isSuccess() && result.getData() != null && !result.getData().isEmpty()) {
                        // 创建表格显示最近播放歌曲
                        GridPane recentPlayGrid = createRecentPlayGrid(result.getData());
                        container.getChildren().add(recentPlayGrid);
                    } else {
                        // 显示空数据提示
                        VBox emptyBox = createEmptyDataView();
                        container.getChildren().add(emptyBox);
                    }
                });
            } catch (Exception e) {
                log.error("加载最近播放数据失败", e);
                Platform.runLater(() -> {
                    // 移除加载指示器
                    container.getChildren().remove(loadingBox);

                    // 显示错误提示
                    Label errorLabel = new Label("加载失败: " + e.getMessage());
                    errorLabel.setStyle("-fx-text-fill: #c00; -fx-font-size: 16px;");

                    VBox errorBox = new VBox(errorLabel);
                    errorBox.setAlignment(Pos.CENTER);
                    errorBox.setPadding(new Insets(50, 0, 0, 0));

                    container.getChildren().add(errorBox);
                });
            }
        }).start();
    }

    /**
     * 创建最近播放表格
     */
    private GridPane createRecentPlayGrid(List<SongPlayHistoryResp> historyList) {
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);
        grid.setPadding(new Insets(10, 0, 10, 0));

        // 添加表头
        Label numberLabel = new Label("#");
        numberLabel.setStyle("-fx-font-weight: bold;");
        grid.add(numberLabel, 0, 0);

        Label titleLabel = new Label("歌曲");
        titleLabel.setStyle("-fx-font-weight: bold;");
        grid.add(titleLabel, 1, 0);

        Label artistLabel = new Label("歌手");
        artistLabel.setStyle("-fx-font-weight: bold;");
        grid.add(artistLabel, 2, 0);

        Label albumLabel = new Label("专辑");
        albumLabel.setStyle("-fx-font-weight: bold;");
        grid.add(albumLabel, 3, 0);

        Label timeLabel = new Label("播放时间");
        timeLabel.setStyle("-fx-font-weight: bold;");
        grid.add(timeLabel, 4, 0);

        // 添加歌曲行
        for (int i = 0; i < historyList.size(); i++) {
            addHistoryRowToGrid(grid, historyList.get(i), i);
        }

        // 设置列宽
        ColumnConstraints col1 = new ColumnConstraints(30);  // 序号列
        ColumnConstraints col2 = new ColumnConstraints(280); // 歌曲列
        ColumnConstraints col3 = new ColumnConstraints(150); // 歌手列
        ColumnConstraints col4 = new ColumnConstraints(180); // 专辑列
        ColumnConstraints col5 = new ColumnConstraints(150); // 播放时间列
        grid.getColumnConstraints().addAll(col1, col2, col3, col4, col5);

        return grid;
    }

    /**
     * 添加历史记录行到表格
     */
    private void addHistoryRowToGrid(GridPane grid, SongPlayHistoryResp history, int index) {
        // 获取歌曲信息
        SongsResp song = history.getSongsResp();
        if (song == null) {
            return; // 如果没有歌曲信息，跳过
        }

        // 行背景 - 用于悬停效果
        HBox rowBackground = new HBox();
        rowBackground.setPrefHeight(50);
        rowBackground.setPrefWidth(800);
        GridPane.setColumnSpan(rowBackground, 5);
        grid.add(rowBackground, 0, index + 1);

        // 序号
        Label number = new Label(String.valueOf(index + 1));
        number.setStyle("-fx-text-fill: #808080;");
        grid.add(number, 0, index + 1);

        // 歌曲（带封面）
        HBox songBox = new HBox(10);
        songBox.setAlignment(Pos.CENTER_LEFT);

        // 歌曲封面
        ImageView cover = new ImageView();
        cover.setFitWidth(40);
        cover.setFitHeight(40);

        // 设置圆角
        Rectangle clip = new Rectangle(40, 40);
        clip.setArcWidth(5);
        clip.setArcHeight(5);
        cover.setClip(clip);

        // 设置封面图片
        if (song.getPicture() != null && !song.getPicture().isEmpty()) {
            cover.setImage(new Image(song.getPicture()));
        } else {
            cover.setImage(new Image("static/default-cover.png"));
        }

        // 歌曲信息
        VBox songInfo = new VBox(3);
        Label songTitle = new Label(song.getTitle());
        songTitle.setStyle("-fx-font-weight: bold;");
        songInfo.getChildren().add(songTitle);

        songBox.getChildren().addAll(cover, songInfo);
        grid.add(songBox, 1, index + 1);

        // 歌手
        Label artist = new Label(song.getArtist());
        artist.setStyle("-fx-text-fill: #404040;");
        grid.add(artist, 2, index + 1);

        // 专辑
        Label album = new Label(song.getAlbum() != null ? song.getAlbum() : "");
        album.setStyle("-fx-text-fill: #606060;");
        album.setWrapText(true);
        grid.add(album, 3, index + 1);

        // 播放时间
        Label playTime = new Label(formatPlayTime(history.getPlayTime()));
        playTime.setStyle("-fx-text-fill: #808080;");
        grid.add(playTime, 4, index + 1);

        // 添加鼠标悬停效果和点击事件
        rowBackground.setOnMouseEntered(e -> {
            rowBackground.setStyle("-fx-background-color: rgba(0,0,0,0.05);");
        });
        rowBackground.setOnMouseExited(e -> {
            rowBackground.setStyle("-fx-background-color: transparent;");
        });
        rowBackground.setOnMouseClicked(event -> {
            // 选择歌曲
            if (onSongSelected != null) {
                onSongSelected.accept(song);
            }
            
            // 双击播放
            if (event.getClickCount() == 2) {
                player.play(song.getFilePath());
            }
        });
    }

    /**
     * 格式化播放时间
     */
    private String formatPlayTime(String timestamp) {
        try {
            long timeMillis = Long.parseLong(timestamp);
            LocalDateTime dateTime = Instant.ofEpochMilli(timeMillis)
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } catch (Exception e) {
            return timestamp;
        }
    }

    /**
     * 创建空数据视图
     */
    private VBox createEmptyDataView() {
        VBox emptyBox = new VBox(15);
        emptyBox.setAlignment(Pos.CENTER);
        emptyBox.setPadding(new Insets(50, 0, 0, 0));

        // 添加图标
        ImageView emptyIcon = new ImageView(new Image("static/play-icon.png", 60, 60, true, true));
        emptyIcon.setOpacity(0.5);

        // 添加文本
        Label emptyLabel = new Label("暂无播放记录");
        emptyLabel.setStyle("-fx-font-size: 18px; -fx-text-fill: #999;");

        Label tipsLabel = new Label("播放歌曲后，将会记录在这里");
        tipsLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #aaa;");

        emptyBox.getChildren().addAll(emptyIcon, emptyLabel, tipsLabel);
        return emptyBox;
    }
} 